package com.xiaok.netty.client.handle;

import com.xiaok.common.protobuf.Command;
import com.xiaok.common.protobuf.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Classname LogicClientHandler
 * @Description TODO
 * @Date 2020/10/8 17:55
 * @Created by xiaok
 */
//SimpleChannelInboundHandler 与 ChannelInboundHandlerAdapter 不同的地方是 不需要手动 调用 ReferenceCountUtil.release(msg);
@Component("logicClientHandler")
public class LogicClientHandler extends SimpleChannelInboundHandler<Message.MessageBase> {
    public Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.netty.clientId}")
    private  String clientId;
    // 连接成功发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
            log.info("与 server 连接成功");
            String data ="this is auth data";
            log.info("clientId: "+clientId);
            ctx.writeAndFlush(createData(clientId,Command.CommandType.AUTH,data).build());

    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("连接断开");
    }
    public Message.MessageBase.Builder createData(String clientId, Command.CommandType cmd,String data){
        Message.MessageBase.Builder msg = Message.MessageBase.newBuilder();
        msg.setClientId(clientId);
        msg.setCmd(cmd);
        msg.setData(data);
        return msg;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message.MessageBase msg) throws Exception {
        Command.CommandType cmd = msg.getCmd();
        if(cmd.equals(Command.CommandType.PUSH_DATA_BACK)){ //服务器回写的数据
            String data = msg.getData(); // 如果是对象则格式化
            log.info("服务器接收的数据: "+data);
            // 回写数据
            ctx.writeAndFlush(createData(clientId,Command.CommandType.PUSH_DATA,"client data"));
        }

        ctx.fireChannelRead(msg);
    }
}
